/*
@(#)UserController   2024-11-08
 
Copyright (c) 2011-2024 杭州湖畔网络技术有限公司 
保留所有权利 
本软件为杭州湖畔网络技术有限公司所有及包含机密信息，须遵守其相关许可证条款进行使用。
Copyright (c) 2011-2024 HUPUN Network Technology CO.,LTD.
All rights reserved.
This software is the confidential and proprietary information of HUPUN
Network Technology CO.,LTD("Confidential Information").  You shall not
disclose such Confidential Information and shall use it only in
accordance with the terms of the license agreement you entered into with HUPUN.
Website：http://www.hupun.com
*/
package org.obp.upms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.obp.core.result.ApiResult;
import org.obp.data.result.PageResult;
import org.obp.data.support.QueryResolver;
import org.obp.data.utils.ObjectUtils;
import org.obp.upms.domain.request.WorkUserEditParam;
import org.obp.upms.domain.request.WorkUserInsetParam;
import org.obp.upms.domain.response.WorkUserVO;
import org.obp.upms.model.WorkRoleDO;
import org.obp.upms.model.WorkUserDO;
import org.obp.upms.model.WorkUserRoleDO;
import org.obp.upms.query.WorkUserQuery;
import org.obp.upms.service.WorkRoleService;
import org.obp.upms.service.WorkUserRoleService;
import org.obp.upms.service.WorkUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: Jackey 2024/11/8
 */
@RestController
@RequestMapping("/v1/work/user")
@Api(tags = {"用户接口"})
public class UserController {

    @Autowired
    private WorkUserService workUserService;
    @Autowired
    private WorkRoleService workRoleService;
    @Autowired
    private WorkUserRoleService workUserRoleService;

    @ApiOperation("用户分页列表")
    @PostMapping("/pager")
    public ApiResult<PageResult<WorkUserVO>> userPager(@RequestBody WorkUserQuery query) {
        IPage pageParam = query.pageParam();
        QueryWrapper<WorkUserDO> queryWrapper = QueryResolver.buildQuery(query);
        if (!CollectionUtils.isEmpty(query.getRoleId())) {
            List<WorkUserRoleDO> relations = workUserRoleService.lambdaQuery()
                    .in(WorkUserRoleDO::getRoleId, query.getRoleId()).list();
            if (CollectionUtils.isEmpty(relations)) {
                return ApiResult.ok(PageResult.ofEmpty(query.getPageNum(), query.getPageSize()));
            }
            List<String> userIds = relations.stream().map(WorkUserRoleDO::getUserId).collect(Collectors.toList());
            queryWrapper.lambda().in(WorkUserDO::getId, userIds);
        }
        queryWrapper.lambda().orderByDesc(WorkUserDO::getGmtCreated);
        IPage<WorkUserDO> pageDO = workUserService.page(pageParam, queryWrapper);
        PageResult<WorkUserDO> pageResultDO = new PageResult<>(pageDO);

        List<String> userIds = pageResultDO.getData().stream().map(WorkUserDO::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(userIds)) {
            return ApiResult.ok(PageResult.ofEmpty(query.getPageNum(), query.getPageSize()));
        }

        Map<String, List<WorkRoleDO>> userRoleMap = workRoleService.getRolesByUserIds(userIds);
        PageResult<WorkUserVO> resultPage = ObjectUtils.copyPage(pageResultDO, WorkUserVO.class, (source, target) -> {
            List<WorkRoleDO> userRoles = userRoleMap.get(source.getId());
            if (!CollectionUtils.isEmpty(userRoles)) target.setUserRoles(userRoles);
        });
        return ApiResult.ok(resultPage);
    }

    @ApiOperation("用户新增功能")
    @PostMapping("/insert")
    public ApiResult<WorkUserVO> userInsert(@Validated @RequestBody WorkUserInsetParam user) {
        WorkUserDO workUserDO = ObjectUtils.copy(user, WorkUserDO.class);
        workUserDO = workUserService.insert(workUserDO, user.getUserRoles());

        WorkUserVO workUserVO = ObjectUtils.copy(workUserDO, WorkUserVO.class);
        workUserVO.setUserRoles(user.getUserRoles());
        return ApiResult.ok(workUserVO);
    }

    @ApiOperation("用户更新功能")
    @PostMapping("/update")
    public ApiResult<String> userUpdate(@Validated @RequestBody WorkUserEditParam user) {
        WorkUserDO workUserDO = ObjectUtils.copy(user, WorkUserDO.class);
        workUserService.update(workUserDO, user.getUserRoles());
        return ApiResult.ok();
    }

}